package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.google.gson.Gson;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.domain.WantdeliverDomain;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;

import org.xutils.common.Callback;
import org.xutils.common.util.DensityUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by Administrator on 2017/8/9.
 */

public class WantQiangdanActivity extends AppCompatActivity implements AMap.OnMyLocationChangeListener, AMapLocationListener {


    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.index_head)
    RelativeLayout indexHead;
    @BindView(R.id.bottom)
    RelativeLayout bottom;

    private double mCurrentLat = 0.0;
    private double mCurrentLon = 0.0;
    private float mCurrentAccracy;
    boolean isFirstLoc = true; // 是否首次定位

     Dialog dialog;
    @BindView(R.id.mapview)
    MapView mapview;
    private AMap aMap=null;
    private AmapLocationService amapLocationService;
    public     ArrayList<Marker> markers=null;
    private String fromprovince="";
    private String fromcity="";
    private String fromarea="";
    private String toprovince="";
    private String tocity="";
    private String toarea="";
    private boolean isFirst=true;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wantqiangdao);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);
        fromprovince=getIntent().getStringExtra("fromprovince");
        fromcity=getIntent().getStringExtra("fromcity");
        fromarea=getIntent().getStringExtra("fromarea");
        toprovince=getIntent().getStringExtra("toprovince");
        tocity=getIntent().getStringExtra("tocity");
        toarea=getIntent().getStringExtra("toarea");
        mapview.onCreate(savedInstanceState);
        if(aMap==null){
            aMap=mapview.getMap();
       //     aMap.moveCamera(CameraUpdateFactory.zoomTo(18));
        }
        final UiSettings uiSettings =  aMap.getUiSettings();
        uiSettings.setLogoBottomMargin(-50);//隐藏logo
        //开启室内地图
        aMap.showIndoorMap(true);
        //是否开启指南针
        aMap.getUiSettings().setCompassEnabled(false);
        //是否开启定位按钮
        aMap.setMyLocationEnabled(true);
        aMap.getUiSettings().setMyLocationButtonEnabled(false); //显示默认的定位按钮
        aMap.getUiSettings().setScaleControlsEnabled(true);//控制比例尺控件是否显示

        //J监听点击事件
        aMap.setOnMyLocationChangeListener(this);
        aMap.setTrafficEnabled(true);
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                WantdeliverDomain.DataBean dataBean= (WantdeliverDomain.DataBean) markers.get(0).getObject();
                Map<String,Object> map=new HashMap<>();
                map.put("data",dataBean);
                Tools.redirectActivity(WantQiangdanActivity.this,QiangOrderInfoActivity.class,map);
                return false;
            }
        });
        MyLocationStyle myLocationStyle= new MyLocationStyle();//初始化定位蓝点样式类;
        //  MyLocationStyle strokeColor();//设置定位蓝点精度圆圈的边框颜色的方法。
        //设置定位蓝点精度圆圈的填充颜色的方法。
        // myLocationStyle.radiusFillColor(getResources().getColor(R.color.default_theme));
        myLocationStyle.radiusFillColor(getResources().getColor(R.color.translucent));
        myLocationStyle.strokeWidth(0.0f);
        myLocationStyle.strokeColor(getResources().getColor(R.color.translucent));
        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE_NO_CENTER);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(1000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        //aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        //信息窗口
        initComponent();
//        amapLocationService=new AmapLocationService(this);
//        amapLocationService.registerListener(this);
//        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
//        amapLocationService.start();
    }
    public AMapLocationClientOption getDefaultAmapLocationOptions(){
        AMapLocationClientOption mLocationOption=null;
        if(mLocationOption==null){
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Battery_Saving);
            mLocationOption.setLocationCacheEnable(true);
        //   mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷1新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return  mLocationOption;
    }
    private void initComponent() {

 }
    @OnClick(value = {R.id.backbt, R.id.kuaisu_bt})
    public void onMyClick(View view){
        switch (view.getId()){
            case R.id.backbt:
                finish();
                break;
            case R.id.kuaisu_bt:
                     if(markers!=null&&markers.size()!=0){
                        WantdeliverDomain.DataBean dataBean= (WantdeliverDomain.DataBean) markers.get(0).getObject();
                          Map<String,Object> map=new HashMap<>();
                          map.put("data",dataBean);
                       Tools.redirectActivity(this,QiangOrderInfoActivity.class,map);
                     }else{
                         Toast.makeText(getApplicationContext(),"尚未匹配到相关订单",Toast.LENGTH_SHORT).show();
                     }
                break;

        }
    }

    @Override
    public void onMyLocationChange(Location location) {
          if(location==null){
              return;
          }
        if(isFirst==true){
            aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                    new LatLng(location.getLatitude(),location.getLongitude()),21));
            isFirst=false;
            query();
        }

    }
    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if(aMapLocation==null){
            return;
        }
//        if(isFirstLoc){

//            isFirstLoc=false;
//        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        query();
    }
    public void query(){
        System.out.println("***************************query");
        Map<String,String> map=new HashMap<>();
     List<User> userList= Xutils.queryAll(getApplication(),User.class);
         if(userList==null||userList.size()==0){
             map.put("userId","0");

         }else{
             map.put("userId",""+userList.get(0).getUserId());
         }
        map.put("fromProvince",""+fromcity);
        map.put("fromCity",""+fromcity);
        map.put("fromArea",""+fromarea);
        map.put("toProvince",""+toprovince);
        map.put("toCity",""+tocity);
        map.put("toArea",""+toarea);
        Xutils.POST(HttpUrl.mywantdeliverquerymapbylocation, map, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                System.out.println("***************************result:*"+result);
                Gson gson=new Gson();
                WantdeliverDomain domain=gson.fromJson(result, WantdeliverDomain.class);
                System.out.println("***************************result:*");
                switch (domain.getState()){
                    case HttpCode.SUCCESS:
                        if(domain.getData()!=null&&domain.getData().size()!=0){
                            System.out.println("**********result:*"+domain.getData().size());
                            if (markers!= null) {
                                for (int i = 0; i < markers.size(); i++) {
                                    Marker options = markers.get(i);
                                    options.remove();
                                }
                                markers.removeAll(markers);
                            }else{
                                markers=new ArrayList<Marker>();
                            }

                            for(int i=0;i<domain.getData().size();i++){
                                System.out.println("**********i"+i);
                                WantdeliverDomain.DataBean  dataBean=domain.getData().get(i);
                                MarkerOptions markerOptions=new MarkerOptions();
                                //是否可以拖拽定位点
                                markerOptions.draggable(false);
                                //设置好经度，纬度坐标
                                LatLng latLng=new LatLng(Double.parseDouble(dataBean.getFromLatitude()),Double.parseDouble(dataBean.getFromLongitude()));
                                //设置好坐标标题
                                markerOptions.title(dataBean.getUserName()+"");
                                //设置定位点的显示效果
                                markerOptions.setFlat(true);//设置marker平贴地图效果
                                markerOptions.infoWindowEnable(false);
                                markerOptions.setGps(false);
                                Marker marker=aMap.addMarker(markerOptions);
                                marker.setPosition(latLng);
                                marker.setIcon(BitmapDescriptorFactory.fromView(View.inflate(WantQiangdanActivity.this, R.layout.circle_views, null)));
                                marker.setObject(dataBean);
                                markers.add(marker);
                            }
                            for(int i=0;i<markers.size();i++){
                                WantdeliverDomain.DataBean  dataBean=domain.getData().get(i);
                                final Marker marker = markers.get(i);
                                Glide.with(getApplicationContext())
                                        .load(dataBean.getUserAvatarpath())
                                        .asBitmap()
                                        .animate(R.anim.fade_in)
                                        .override(DensityUtil.dip2px(35), DensityUtil.dip2px(35))
                                        .into(new SimpleTarget<Bitmap>() {
                                            @Override
                                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                                View view = View.inflate(WantQiangdanActivity.this, R.layout.circle_views, null);
                                                ((CircleImageView) view.findViewById(R.id.cir_icon))
                                                        .setImageBitmap(resource);
                                                marker.setIcon(BitmapDescriptorFactory.fromView(view));
                                            }
                                        });
                            }

                        }
                        break;
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }



    @Override
    protected void onResume() {
        super.onResume();
        mapview.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapview.onPause();
    }



    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapview.onSaveInstanceState(outState);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mapview.onDestroy();
//        if (amapLocationService != null) {
//            amapLocationService.unregisterListener(this);
//            amapLocationService.stop();
//        }
    }

}
